import React, { useState, useEffect } from 'react'
import { useSearchParams } from 'react-router-dom'
import LogViewer from '../components/LogViewer'
import { ipcService } from '../services/ipc-service'
import { useSimpleQuery } from '../hooks/use-simple-query'

interface TaskLogEntry {
  id: string
  level: 'info' | 'warn' | 'error' | 'debug'
  message: string
  data?: any
  source?: string
  timestamp: Date
}

interface TaskLogsResponse {
  items: TaskLogEntry[]
  total: number
  page: number
  pageSize: number
  hasMore: boolean
}

const TaskLogsPage: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams()
  const [selectedLevel, setSelectedLevel] = useState<string>('')
  const [selectedTaskId, setSelectedTaskId] = useState<string>('')
  const [page, setPage] = useState(1)
  const [logs, setLogs] = useState<TaskLogEntry[]>([])
  const [isLoading, setIsLoading] = useState(false)

  // 从URL参数获取任务ID
  const taskIdFromUrl = searchParams.get('taskId') || ''

  // 加载日志数据
  const loadLogs = async (pageNum: number = 1, append: boolean = false) => {
    setIsLoading(true)
    try {
      let response: TaskLogsResponse

      if (selectedTaskId) {
        // 获取特定任务的日志
        response = await ipcService.invoke('task:get-logs-by-id', selectedTaskId, pageNum, 50)
      } else {
        // 获取所有日志
        response = await ipcService.invoke('task:get-logs', pageNum, 50, selectedLevel || undefined)
      }

      if (append) {
        setLogs(prev => [...prev, ...response.items])
      } else {
        setLogs(response.items)
      }

      setPage(pageNum)
    } catch (error) {
      console.error('加载日志失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 初始化时加载日志
  useEffect(() => {
    if (taskIdFromUrl) {
      setSelectedTaskId(taskIdFromUrl)
    }
    loadLogs(1, false)
  }, [selectedLevel, selectedTaskId, taskIdFromUrl])

  // 加载更多日志
  const loadMore = () => {
    loadLogs(page + 1, true)
  }

  // 刷新日志
  const refreshLogs = () => {
    loadLogs(1, false)
  }

  // 清空筛选
  const clearFilters = () => {
    setSelectedLevel('')
    setSelectedTaskId('')
    setSearchParams({})
  }

  // 日志级别选项
  const levelOptions = [
    { value: '', label: '全部级别' },
    { value: 'error', label: '错误' },
    { value: 'warn', label: '警告' },
    { value: 'info', label: '信息' },
    { value: 'debug', label: '调试' }
  ]

  return (
    <div className="p-6 space-y-6">
      {/* 筛选器 */}
      <div className="bg-white p-4 rounded-lg border border-gray-200">
        <div className="flex flex-wrap items-center gap-4">
          {/* 级别筛选 */}
          <div className="flex items-center space-x-2">
            <label className="text-sm font-medium text-gray-700">级别:</label>
            <select
              value={selectedLevel}
              onChange={(e) => setSelectedLevel(e.target.value)}
              className="px-3 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {levelOptions.map(option => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>

          {/* 清空筛选 */}
          {(selectedLevel || selectedTaskId) && (
            <button
              onClick={clearFilters}
              className="px-3 py-1 text-sm text-gray-600 hover:text-gray-800 underline"
            >
              清空筛选
            </button>
          )}
          <button
            onClick={refreshLogs}
            disabled={isLoading}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
          >
            {isLoading ? '刷新中...' : '刷新'}
          </button>
          {/* 日志统计 */}
          <div className="ml-auto text-sm text-gray-500">
            共 {logs.length} 条日志
          </div>
        </div>
      </div>

      {/* 日志查看器 */}
      <div className="bg-white rounded-lg border border-gray-200">
        <LogViewer
          logs={logs}
          maxHeight="600px"
          autoScroll={true}
          showTimestamp={true}
          showLevel={true}
          className="border-0"
        />

        {/* 加载更多按钮 */}
        {logs.length > 0 && (
          <div className="p-4 border-t border-gray-200 text-center">
            <button
              onClick={loadMore}
              disabled={isLoading}
              className="px-4 py-2 text-sm text-blue-600 hover:text-blue-800 disabled:opacity-50"
            >
              {isLoading ? '加载中...' : '加载更多'}
            </button>
          </div>
        )}
      </div>

      {/* 空状态 */}
      {logs.length === 0 && !isLoading && (
        <div className="bg-white rounded-lg border border-gray-200 p-8 text-center">
          <div className="text-gray-400 text-4xl mb-4">📝</div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">暂无日志</h3>
          <p className="text-gray-600">
            {selectedTaskId || selectedLevel ? '当前筛选条件下没有找到日志记录' : '还没有任务日志记录'}
          </p>
        </div>
      )}
    </div>
  )
}

export default TaskLogsPage
